﻿Imports System.Data.OleDb

' Sequence Object generater class.
' Access's auto-number is not very easy to get back when doing
' inserts programatically and Access also doesn't provide "sequence" object functionality
' so this home baked sequence generator has to do.
Class SequenceFactoryImpl
    Implements SequenceFactory

    Private _conn As OleDb.OleDbConnection
    Private idMap As Dictionary(Of Tables, Long)

    Sub New(conn As OleDb.OleDbConnection)

        _conn = conn
        idMap = New Dictionary(Of Tables, Long)
        Dim seed As Object
        Dim command As New OleDbCommand()
        command.Connection = conn

        For Each table As Tables In System.Enum.GetValues(GetType(Tables))
            command.CommandText = "select max(id) from " & table.ToString & ";"
            seed = command.ExecuteScalar()
            idMap.Add(table, If(IsDBNull(seed), 0, CLng(seed)))
        Next

    End Sub

    Public Function nextIdFor(ByVal table As Tables) As Long Implements SequenceFactory.nextIdFor
        idMap(table) += 1
        Return idMap(table)
    End Function

End Class
